using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using Lib.Approval;
using Lib.Helper;
using Lib.Mail;
using MSIACCSL2.ApplicationStateServices;
using MSIACCSL2.Command;
using MSIACCSL2.CostCenterServices;
using MSIACCSL2.CustomerServices;
using MSIACCSL2.InventoryServices;
using MSIACCSL2.SalesInvoiceServices;
using MSIACCSL2.SalesReturnServices;
using MSIACCSL2.Views.SalesReturn;
using MSIACCSL2.WarehouseServices;
using WcfService1.DTO;
using DeleteDetailCompletedEventArgs = MSIACCSL2.SalesReturnServices.DeleteDetailCompletedEventArgs;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.SalesReturnServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.SalesReturnServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = MSIACCSL2.SalesReturnServices.SaveCompletedEventArgs;


namespace MSIACCSL2.ViewModels
{
    public class SalesReturnViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static Search frmSearch;
        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        public static Completed OnSearchCompleted;
        private static NavigationService _NavigationService;
        private readonly AplicationStateServicesClient ApplicationService;
        private readonly CostCenterServicesClient CostCenterClient;
        private readonly CustomerServicesClient CustomerClient;
        private readonly SalesInvoiceServicesClient SalesInvoiceClient;
        private readonly SalesReturnServicesClient client;
        private readonly WarehouseServicesClient WarehouseClient;

        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private bool IsUsed;
        private ObservableCollection<int> Pages;
        private ObservableCollection<CostCenterDTO> _CostCenters;
        private Visibility _CustomerVisibility;
        private ObservableCollection<CustomerDTO> _Customers;
        private bool _IsBusy;
        private bool _IsEnabled;
        private ObservableCollection<SalesInvoiceDTO> _SalesInvoices;
        private SalesReturnDTO _SalesReturn;
        private PagedCollectionView _SalesReturns;
        private List<string> _errors;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private Dictionary<string, object> criteria;
        private string expression;
        private ObservableCollection<WarehouseDTO> _Warehouses;


        public SalesReturnViewModel()
        {
            IsEnabled = true;
            if (!DesignerProperties.IsInDesignTool)
            {
                client = new SalesReturnServicesClient();
                CustomerClient = new CustomerServicesClient();
                SalesInvoiceClient = new SalesInvoiceServicesClient();
                CostCenterClient = new CostCenterServicesClient();
                WarehouseClient = new WarehouseServicesClient();
              

                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveSalesReturn, CanSave);
                New = new DelegateCommand(NewSalesReturn, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchSalesReturn, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                LoadInvoiceCommand = new DelegateCommand(LoadInvoice, CanLoadInvoiceCommand);
                validationHandler = new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;
                CustomerVisibility = Visibility.Collapsed;
                ApplicationService = new AplicationStateServicesClient();

                if (mode == Mode.Edit)
                {
                    PrepareEdit();
                }
                else if (mode == Mode.Search)
                {
                    SalesReturn = new SalesReturnDTO();
                    SalesReturn.SRDate = null;
                    //GetSalesInvoiceList();
                }
                else if (mode == Mode.Add)
                {
                    PrepareAdd();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }


        public ObservableCollection<CostCenterDTO> CostCenters
        {
            get { return _CostCenters; }
            private set
            {
                if (CostCenters == value) return;
                _CostCenters = value;
                FirePropertyChanged("CostCenters");
            }
        }


        public PagedCollectionView SalesReturns
        {
            get { return _SalesReturns; }

            private set
            {
                if (SalesReturns == value) return;
                _SalesReturns = value;
                int i = (CurrentPage*30);
                foreach (object SalesReturn in SalesReturns)
                {
                    i += 1;

                    ((SalesReturnDTO) SalesReturn).No = i;
                }
                FirePropertyChanged("SalesReturns");
                SalesReturns.CollectionChanged += SalesReturn_CollectionChanged;
            }
        }

        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public ObservableCollection<CustomerDTO> Customers
        {
            get { return _Customers; }
            private set
            {
                if (Customers == value) return;
                _Customers = value;
                FirePropertyChanged("Customers");
            }
        }

        public ObservableCollection<SalesInvoiceDTO> SalesInvoices
        {
            get { return _SalesInvoices; }
            private set
            {
                if (SalesInvoices == value) return;
                _SalesInvoices = value;
                FirePropertyChanged("SalesInvoices");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }

        public Visibility CustomerVisibility
        {
            get { return _CustomerVisibility; }
            internal set
            {
                _CustomerVisibility = value;
                FirePropertyChanged("CustomerVisibility");
            }
        }


        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public SalesReturnDTO SalesReturn
        {
            get { return _SalesReturn; }
            private set
            {
                if (SalesReturn == value) return;
                _SalesReturn = value;
                FirePropertyChanged("SalesReturn");
            }
        }

        public ObservableCollection<WarehouseDTO> Warehouses
        {
            get { return _Warehouses; }
            private set
            {
                if (Warehouses == value) return;
                _Warehouses = value;
                FirePropertyChanged("Warehouses");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }

        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }

        public bool IsEnabled
        {
            get { return _IsEnabled; }
            internal set
            {
                _IsEnabled = value;
                FirePropertyChanged("IsEnabled");
            }
        }


        public ICommand LoadInvoiceCommand { get; set; }

        private void PrepareEdit()
        {
            //GetCustomerList();
            //GetSalesInvoiceList();
          
            SalesReturn = (SalesReturnDTO) Navigation.Args;
            GetSalesReturn(SalesReturn.SRNo);
            CekTransaksi();
        }


        private void PrepareAdd()
        {
            GetCostCenterList();
            GetWarehouseList();
            //GetSalesInvoiceList();
            SalesReturn = new SalesReturnDTO();
            SalesReturn.SalesReturnDetails = new ObservableCollection<SalesReturnDetailDTO>();
            var SalesReturnDetail = new SalesReturnDetailDTO();
            SalesReturnDetail.Inventory = new InventoryDTO();
            SalesReturn.SalesReturnDetails.Add(SalesReturnDetail);
            
            //CekTransaksi();
        }

        private void GetSalesReturn(string SRNo)
        {
            client.GetSalesReturnCompleted += client_GetSalesReturnCompleted;
            client.GetSalesReturnAsync(SRNo);
        }

        private void client_GetSalesReturnCompleted(object sender, GetSalesReturnCompletedEventArgs e)
        {
            client.GetSalesReturnCompleted -= client_GetSalesReturnCompleted;
            SalesReturn = e.Result;
            if (SalesReturn.SalesReturnDetails == null)
                SalesReturn.SalesReturnDetails = new ObservableCollection<SalesReturnDetailDTO>();
            if (SalesReturn.SalesReturnDetails.Count == 0)
                SalesReturn.SalesReturnDetails.Add(new SalesReturnDetailDTO());
            GetCostCenterList();
            GetWarehouseList();
        }


        private void GetCostCenterList()
        {
            CostCenterClient.GetAllCostCenterCompleted += CostCenterClient_GetAllCostCenterCompleted;
            CostCenterClient.GetAllCostCenterAsync();
        }

        private void CostCenterClient_GetAllCostCenterCompleted(object sender, GetAllCostCenterCompletedEventArgs e)
        {
            CostCenterClient.GetAllCostCenterCompleted -= CostCenterClient_GetAllCostCenterCompleted;
            CostCenters = e.Result;
            if (SalesReturn != null)
                if (SalesReturn.CostCenter != null)
                {
                    SalesReturn.CostCenter =
                        CostCenters.FirstOrDefault(x => x.CostCenterId == SalesReturn.CostCenter.CostCenterId);
                    GetSalesInvoiceList(SalesReturn.CostCenter);
                }
        }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void SalesReturn_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveSalesReturn(Object salesReturn)
        {
            //SalesReturn = (SalesReturnDTO) salesReturn;
            if (SalesReturn.SalesReturnDetails.Count == 1)
            {
                //Bila tidak ada yang dipilih di detail maka details harus dihapus
                if (SalesReturn.SalesReturnDetails[0].Inventory == null)
                    SalesReturn.SalesReturnDetails.Clear();
            }
            Validate();
            if (Errors.Count > 0) return;
            SalesReturn.created_by = GlobalVar.User.UserID;
            SalesReturn.modified_by = GlobalVar.User.UserID;
            IsBusy = true;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync(SalesReturn, mode);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            if (e.Error != null) Validate(e.Error.ToString());
            client.SaveCompleted -= client_SaveCompleted;
            mode = (Mode) e.UserState;
            if (e.Result)
            {
                IsBusy = false;
                ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/SalesReturn/Index", UriKind.Relative));
            }
            else
            {
                IsBusy = false;
                MessageBox.Show("Simpan Gagal, Periksa data Anda!");
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            SalesReturns = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewSalesReturn(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/SalesReturn/frmAdd", UriKind.Relative));
        }


        private void SearchSalesReturn(Object param)
        {
            mode = Mode.Search;
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
             criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in SalesReturn.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(SalesReturn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(SalesReturn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(SalesReturn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(SalesReturn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(SalesReturn, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(SalesReturn, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(SalesReturn, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(SalesReturn, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(SalesReturn, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(SalesReturn, null));
                }
            }

            expression = string.Empty;
            if (frmSearch.rblOr.IsChecked ?? false) expression = "OR";
            else expression = "AND";
            SalesReturnSearch(criteria, expression,1);
        }

        private void SalesReturnSearch(Dictionary<String, Object> criteria, string expression,int page)
        {
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, page);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            SalesReturns = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }
            IsBusy = false;
        }

        public void GetSalesInvoiceList(CostCenterDTO costCenter)
        {
            if (SalesInvoices != null && SalesInvoices.Count > 0)return;
            SalesInvoiceClient.GetSalesInvoiceListByCostCenterCompleted += new EventHandler<GetSalesInvoiceListByCostCenterCompletedEventArgs>(SalesInvoiceClient_GetSalesInvoiceListByCostCenterCompleted);
            SalesInvoiceClient.GetSalesInvoiceListByCostCenterAsync(costCenter);
        }

        void SalesInvoiceClient_GetSalesInvoiceListByCostCenterCompleted(object sender, GetSalesInvoiceListByCostCenterCompletedEventArgs e)
        {
            SalesInvoiceClient.GetSalesInvoiceListByCostCenterCompleted -= new EventHandler<GetSalesInvoiceListByCostCenterCompletedEventArgs>(SalesInvoiceClient_GetSalesInvoiceListByCostCenterCompleted);
            e.Result.Add(SalesReturn.SalesInvoice);
            SalesInvoices = e.Result;
           
            if (SalesReturn != null)
            {
                if (SalesReturn.SalesInvoice == null) return;
                SalesInvoices.Add(SalesReturn.SalesInvoice);
                SalesReturn.SalesInvoice =
                    SalesInvoices.FirstOrDefault(s => s.SINo == SalesReturn.SalesInvoice.SINo);
            }
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            SalesReturn = null;
            if (SalesReturns != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (mode == Mode.Search)
                    SalesReturnSearch(criteria, expression, (int)pageIndex + 1);
                else if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            SalesReturn = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (SalesReturns == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();
            //if (string.IsNullOrEmpty(SalesReturn.SRNo))
            //    Errors.Add("Nomor SR tidak boleh kosong");
            if (SalesReturn.SalesInvoice == null)
                Errors.Add("Sales Invoice Belum dipilih");
            if (SalesReturn.Warehouse == null)
                Errors.Add("Warehouse Belum dipilih");

            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            if (Errors.Count > 0)
            {
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                MessageVisibility = Visibility.Collapsed;
            }
        }

        public void Cancel(Object param)
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Cancel ?", "Confirmation",
                                                   MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                if (!IsUsed) ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.GoBack();
            }
        }

        public void GetLastNoSalesReturn(Object param)
        {
            if (param == null) return;
            client.GetLastSRNoCompleted +=
                client_GetLastNoSalesReturnCompleted;
            client.GetLastSRNoAsync(param as CostCenterDTO, (param as CostCenterDTO).CostCenterId);
        }

        private void client_GetLastNoSalesReturnCompleted(object sender, GetLastSRNoCompletedEventArgs e)
        {
            client.GetLastSRNoCompleted -=
                client_GetLastNoSalesReturnCompleted;
            string res = e.Result;
            string formatSO = "0000";
            string kodeSO;
            if (e.Result.Length <= 4)
            {
                res = formatSO;
                kodeSO = e.Result;
            }
            else
            {
                res = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[3];
                kodeSO = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[0];
            }
            string soNum = formatSO.Substring(0, formatSO.Length - (int.Parse(res) + 1).ToString().Length) +
                           (int.Parse(res) + 1);

            string costCenter = e.UserState.ToString();
            SalesReturn.SRNo = kodeSO + "/" + costCenter + "/" + DateTime.Now.Year + "/" + soNum;
        }

        public bool CanLoadInvoiceCommand(Object param)
        {
            return true;
        }

        public void LoadInvoice(Object param)
        {
            if (param == null) return;
            var SI = (SalesInvoiceDTO) param;
            SalesInvoiceClient.GetSalesInvoiceCompleted += SalesInvoiceClient_GetSalesInvoiceCompleted;
            SalesInvoiceClient.GetSalesInvoiceAsync(SI.SINo);
        }

        private void SalesInvoiceClient_GetSalesInvoiceCompleted(object sender, GetSalesInvoiceCompletedEventArgs e)
        {
            SalesInvoiceClient.GetSalesInvoiceCompleted -= SalesInvoiceClient_GetSalesInvoiceCompleted;
            SalesReturn.Customer = e.Result.Customer;
            if (e.Result.DeliveryOrder != null)
                if (e.Result.DeliveryOrder.Warehouse != null)
                    SalesReturn.Warehouse =
                        Warehouses.FirstOrDefault(x => x.KodeWarehouse == e.Result.DeliveryOrder.Warehouse.KodeWarehouse);

            SalesReturn.SalesReturnDetails.Clear();
            foreach (SalesInvoiceDetailDTO salesInvoiceDetail in e.Result.SalesInvoiceDetails)
            {
                var srDetail = new SalesReturnDetailDTO();
                srDetail.Inventory =
                    salesInvoiceDetail.Inventory;
                srDetail.Price = salesInvoiceDetail.Price;
                srDetail.Panjang = salesInvoiceDetail.Panjang;
                srDetail.Lebar = salesInvoiceDetail.Lebar;
                srDetail.QtyUnit = salesInvoiceDetail.Qty;
                srDetail.Tinggi = salesInvoiceDetail.Sheet;

                if (salesInvoiceDetail.DiscountType == "%")
                    srDetail.Discount = (salesInvoiceDetail.Price * salesInvoiceDetail.Qty) * (salesInvoiceDetail.Discount/100);
                else
                    srDetail.Discount = salesInvoiceDetail.Discount;
                SalesReturn.SalesReturnDetails.Add(srDetail);
            }
        }

        public void GetCustomer(Object param)
        {
            CustomerClient.GetCustomerListCompleted += CustomerClient_GetCustomerListCompleted;
            CustomerClient.GetCustomerListAsync(param.ToString());
        }

        private void CustomerClient_GetCustomerListCompleted(object sender, GetCustomerListCompletedEventArgs e)
        {
            CustomerClient.GetCustomerListCompleted -= CustomerClient_GetCustomerListCompleted;
            Customers = e.Result;
            CustomerVisibility = Visibility.Visible;
            EventAggregator.PublishMessage("CustomerSelect", string.Empty);
        }

        public void CustomerSelected(Object param)
        {
            SalesReturn.Customer = ((CustomerDTO) param);
            CustomerVisibility = Visibility.Collapsed;
        }

        public void Print(Object param)
        {
            Navigation.MyNavigation.Navigate(new Uri("/SalesReturn/PrintPreviewSR", UriKind.Relative));
            Navigation.Args = param;
        }

        public void SendEmail(Object param)
        {
            ChooseDestination chooseDestination = new ChooseDestination();
            chooseDestination.Show();
            EventAggregator.RegisterMessage("SendDestination", (x) =>
            {
                IsBusy = true;
                client.SendEmailCompleted += client_SendEmailCompleted;
                client.SendEmailAsync(param as SalesReturnDTO, (x as WarehouseDTO).EmailFolder);
            });
         
        }

        private void client_SendEmailCompleted(object sender, SendEmailCompletedEventArgs e)
        {
            IsBusy = false;
            client.SendEmailCompleted -= client_SendEmailCompleted;
            if (e.Result) MessageBox.Show("Pengiriman Selesai");
        }

        public void CekTransaksi()
        {
            ApplicationService.IsTransactionUsedCompleted += ApplicationService_IsTransactionUsedCompleted;
            if (string.IsNullOrEmpty(SalesReturn.SRNo))
            {
                ApplicationService.IsTransactionUsedAsync(SalesReturn.ToString(), GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = SalesReturn.ToString();
            }
            else
            {
                ApplicationService.IsTransactionUsedAsync(SalesReturn.SRNo, GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = SalesReturn.SRNo;
            }
        }

        private void ApplicationService_IsTransactionUsedCompleted(object sender, IsTransactionUsedCompletedEventArgs e)
        {
            ApplicationService.IsTransactionUsedCompleted -= ApplicationService_IsTransactionUsedCompleted;
            IsUsed = e.Result;
            mode = (Mode) e.UserState;
            if (IsUsed)
            {
                MessageBox.Show("Transaksi sedang digunakan!");
                if (mode == Mode.Add) //If Add Mode
                {
                    mode = Mode.Idle;
                    Navigation.MyNavigation.Navigate(new Uri("/SalesReturn/Index", UriKind.Relative));
                }
                else //Edit Mode just view Only
                {
                    IsEnabled = false;
                }
            }
        }

        private void ClearTransaksi(Mode mode)
        {
            ApplicationService.ClearTransactionCompleted += ApplicationService_ClearTransactionCompleted;
            if (mode == Mode.Add)
                ApplicationService.ClearTransactionAsync(SalesReturn.ToString(), GlobalVar.User);
            else
                ApplicationService.ClearTransactionAsync(SalesReturn.SRNo, GlobalVar.User);
        }

        private void ApplicationService_ClearTransactionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ApplicationService.ClearTransactionCompleted -= ApplicationService_ClearTransactionCompleted;
        }

        public void GetWarehouseList()
        {
            WarehouseClient.GetAllWarehouseCompleted += WarehouseClient_GetAllWarehouseCompleted;
            WarehouseClient.GetAllWarehouseAsync();
        }

        private void WarehouseClient_GetAllWarehouseCompleted(object sender, GetAllWarehouseCompletedEventArgs e)
        {
            WarehouseClient.GetAllWarehouseCompleted -= WarehouseClient_GetAllWarehouseCompleted;
            Warehouses = e.Result;
            if (SalesReturn != null)
                if (SalesReturn.Warehouse != null)
                    SalesReturn.Warehouse =
                        Warehouses.FirstOrDefault(w => w.KodeWarehouse == SalesReturn.Warehouse.KodeWarehouse);
        }

        public void CloseStatus()
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Close this Transaction ?", "Confirmation",
                                                MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                client.UpdateStatusCompleted += new EventHandler<AsyncCompletedEventArgs>(client_UpdateStatusCompleted);
                client.UpdateStatusAsync(SalesReturn, Status.Close);
            }
        }

        void client_UpdateStatusCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.UpdateStatusCompleted -= new EventHandler<AsyncCompletedEventArgs>(client_UpdateStatusCompleted);
            MessageBox.Show("Update Status finished!");
        }
    }


    public class SalesReturnWrapViewModel : ViewModelBase
    {
        private readonly InventoryServiceClient InventoryClient;
        private readonly SalesReturnServicesClient client;
        private ObservableCollection<InventoryDTO> _Inventorys;
        private ObservableCollection<PalletDTO> _Pallets;
        private SalesReturnDetailDTO _SalesReturnDetail;
        private ObservableCollection<WarehouseDTO> _Warehouses;


        public SalesReturnWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new SalesReturnServicesClient();
                InventoryClient = new InventoryServiceClient();
                AddDetailCommand = new DelegateCommand(AddSalesReturnDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeleteSalesReturnDetail, CanDeleteDetailCommand);
                GetInventoryCommand = new DelegateCommand(GetInventory, CanGetInventoryCommand);
                GetTotalDetailCommand = new DelegateCommand(GetTotalDetail, CanGetTotalDetailCommand);
                GetQtyUnitCommand = new DelegateCommand(GetQtyUnit, CanGetInventoryCommand);

                if (SalesReturnViewModel.mode == Mode.Add || SalesReturnViewModel.mode == Mode.Edit)
                {
                   
                }
            }
        }

        public SalesReturnViewModel SalesReturnViewModel { get; set; }

        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }


        public ObservableCollection<InventoryDTO> Inventorys
        {
            get { return _Inventorys; }
            private set
            {
                if (Inventorys == value) return;
                _Inventorys = value;
                FirePropertyChanged("Inventorys");
            }
        }


        public ObservableCollection<PalletDTO> Pallets
        {
            get { return _Pallets; }
            private set
            {
                if (Pallets == value) return;
                _Pallets = value;
                FirePropertyChanged("Pallets");
            }
        }


     


        public SalesReturnDetailDTO SalesReturnDetail
        {
            get { return _SalesReturnDetail; }
            private set
            {
                if (SalesReturnDetail == value) return;
                _SalesReturnDetail = value;
                FirePropertyChanged("SalesReturnDetail");
            }
        }

        public ICommand GetInventoryCommand { get; set; }
        public ICommand GetQtyUnitCommand { get; set; }
        public ICommand GetTotalDetailCommand { get; set; }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            SalesReturnViewModel.mode = Mode.Edit;
            Navigation.MyNavigation.Navigate(new Uri("/SalesReturn/frmAdd", UriKind.Relative));
            Navigation.Args = param;
        }

        public void Delete(Object param)
        {
            DeleteConfirmation deleteConfirmation = new DeleteConfirmation();
            deleteConfirmation.Show();
            EventAggregator.RegisterMessage("ApprovalSucceeded", (x) =>
            {
                deleteConfirmation.Close();
                client.DeleteCompleted += client_DeleteCompleted;
                client.DeleteAsync((SalesReturnDTO)param);
            });

        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            SalesReturnViewModel.mode = Mode.Idle;
            var VM = new SalesReturnViewModel();
        }


        public void GetInventoryList()
        {
            InventoryClient.GetInventoryByCriteriaCompleted +=
                InventoryClient_GetListByCriteriaCompleted;
            InventoryClient.GetInventoryByCriteriaAsync(new Dictionary<string, object>(), null, 1);
        }

        private void InventoryClient_GetListByCriteriaCompleted(object sender,
                                                                GetInventoryByCriteriaCompletedEventArgs e)
        {
            Inventorys = e.Result;
            if (SalesReturnViewModel.SalesReturn != null)
            {
                foreach (SalesReturnDetailDTO SalesReturnDetail in SalesReturnViewModel.SalesReturn.SalesReturnDetails)
                {
                    if (SalesReturnDetail.Inventory == null) continue;
                    SalesReturnDetail.Inventory =
                        Inventorys.FirstOrDefault(s => s.SerialNumber == SalesReturnDetail.Inventory.SerialNumber);
                }
            }
        }


        public void GetInventory(Object param)
        {
            SalesReturnDetail = (SalesReturnDetailDTO) param;
            if (SalesReturnDetail.Inventory == null) SalesReturnDetail.Inventory = new InventoryDTO();
            string SerialNumber = SalesReturnDetail.Inventory.SerialNumber;
            InventoryClient.GetInventoryCompleted +=
                InventoryClient_GetInventoryCompleted;
            InventoryClient.GetInventoryAsync(SerialNumber);
        }

        private void InventoryClient_GetInventoryCompleted(object sender, GetInventoryCompletedEventArgs e)
        {
            InventoryDTO InventoryTemp = e.Result;
            if (null != InventoryTemp && ! string.IsNullOrEmpty(InventoryTemp.SerialNumber))
            {
                SalesReturnDetail.Inventory = InventoryTemp;
                SalesReturnDetail.Panjang = InventoryTemp.Panjang;
                SalesReturnDetail.Lebar = InventoryTemp.Lebar;
                SalesReturnDetail.Tinggi = InventoryTemp.Tinggi;
                //SalesReturnDetail.QtyUnit = InventoryTemp.Warehouses.FirstOrDefault().Qty;
                SalesReturnDetail.Inventory.Item = e.Result.Item;
                SalesReturnDetail.Inventory.SatuanUnit =
                    e.Result.SatuanUnit;
            }else
            {
               MessageBox.Show("Barang tidak ditemukan, coba entry secara manual");
            }
        }

        public void AddSalesReturnDetail(Object param)
        {
            SalesReturnDetail = new SalesReturnDetailDTO();
            SalesReturnDetail.Inventory = new InventoryDTO();
            SalesReturnViewModel.SalesReturn.SalesReturnDetails.Add(SalesReturnDetail);
        }

        public void DeleteSalesReturnDetail(Object param)
        {
            var SalesReturnDetail = (SalesReturnDetailDTO) param;
            if (SalesReturnViewModel.SalesReturn.SalesReturnDetails.Count > 1)
            {
                SalesReturnViewModel.SalesReturn.SalesReturnDetails.Remove(SalesReturnDetail);
                GetTotalDetail(SalesReturnDetail);
            }
        }

        public bool CanGetInventoryCommand(Object param)
        {
            return true;
        }

        public bool CanGetQtyUnit(Object param)
        {
            return true;
        }

        public void GetQtyUnit(Object param)
        {
            SalesReturnDetail = param as SalesReturnDetailDTO;
            if (SalesReturnDetail != null)
                if (SalesReturnDetail.Inventory != null)
                {
                    SalesReturnDetail.QtyUnit = SalesReturnDetail.Inventory.QtyPack *
                                               (SalesReturnDetail.Panjang * SalesReturnDetail.Lebar *
                                                SalesReturnDetail.Tinggi) /
                                               SalesReturnDetail.Inventory.SatuanUnit.Pengali;

                    SalesReturnDetail.QtyUnit = SalesReturnDetail.Inventory.Item.IsRounded
                                                    ? SalesReturnDetail.QtyUnit.Round(2, MidpointRounding.AwayFromZero)
                                                    : SalesReturnDetail.QtyUnit.Round(4, MidpointRounding.AwayFromZero);

                }
        }
                   


        public bool CanGetTotalDetailCommand(Object param)
        {
            return true;
        }

        public void GetTotalDetail(Object param)
        {
            SalesReturnDetail = (SalesReturnDetailDTO) param;
            SalesReturnDetail.TotalDetail = (SalesReturnDetail.Price) -
                                            ((SalesReturnDetail.Price)*SalesReturnDetail.Discount/100);
            SalesReturnViewModel.SalesReturn.Total =
                SalesReturnViewModel.SalesReturn.SalesReturnDetails.Sum(p => p.TotalDetail);
        }

    
    }
}